package com.buaa.springboot.fileupload.entity;

import com.buaa.springboot.fileupload.enumeration.ResponseCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * 给前端的统一响应体，响应体由状态码，状态信息和数据内容三部分构成，
 *
 * @param <T>
 */
@NoArgsConstructor
@Getter
public final class
ResponseMessage<T> {

    private Integer code;

    private String msg;

    private T payload;


    private ResponseMessage(ResponseCode responseCode) {
        this(responseCode, null);
    }

    private ResponseMessage(ResponseCode responseCode, T payload) {
        this.code = responseCode.getCode();
        this.msg = responseCode.getMsg();
        this.payload = payload;
    }

    /**
     * 操作成功并且没有响应内容时调用
     *
     * @param <T> 内容类型
     * @return 响应体
     */
    public static <T> ResponseMessage<T> ok() {
        return new ResponseMessage<>(ResponseCode.SUCCESS);
    }

    /**
     * 操作成功并且有响应内容时调用
     *
     * @param payload 响应内容
     * @param <T>     内容类型
     * @return 响应体
     */
    public static <T> ResponseMessage<T> ok(T payload) {
        return new ResponseMessage<>(ResponseCode.SUCCESS, payload);
    }

    /**
     * 操作失败时调用，用在异常处理类中
     *
     * @param responseCode 响应码
     * @param payload      错误消息
     * @param <T>          消息类型
     * @return 响应体
     */
    public static <T> ResponseMessage<T> error(ResponseCode responseCode, T payload) {
        return new ResponseMessage<>(responseCode, payload);
    }

    /**
     * 操作失败时调用，用在异常处理类中
     *
     * @param responseCode 响应码
     * @param <T>          消息类型
     * @return 响应体
     */
    public static <T> ResponseMessage<T> error(ResponseCode responseCode) {
        return new ResponseMessage<>(responseCode);
    }
}
